//
//  DeviceYaobaiVc.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/3/12.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//
#import "NSDate+YYAdd.h"

#import "DeviceYaobaiVc.h"
#import "DeviceVc.h"



@interface DeviceYaobaiVc ()
@property (nonatomic, strong)UIImage *speed_sel_bg_img;
@property (nonatomic, strong)UIImage *speed_normal_bg_img;
@property (nonatomic, strong)UIImage *time_sel_bg_img;
@property (nonatomic, strong)UIImage *time_normal_bg_img;

@end

@implementation DeviceYaobaiVc

- (IBAction)timeBtnClick:(UIButton *)sender {
    
    
    if (self.counting) {
        return;
    }
    
    sender.userInteractionEnabled = NO;
    
    [self change_status_timeBtn:sender];
    sender.userInteractionEnabled = YES;
}
- (IBAction)speedBtnClick:(UIButton *)sender {
    sender.userInteractionEnabled = NO;
    
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;

    NSMutableArray *dataArr = [NSMutableArray array];
    [dataArr addObject:@{
                         @"reg" : @"range_level"
                         , @"value" : @(sender.tag + 1)
                         }];
    [vc queryWith_cmd:@"dev" data:dataArr];
    sender.userInteractionEnabled = YES;
}
- (void)change_status_speedBtn:(UIButton *)sender {
    sender.selected = YES;
    
    for (UIButton *btn in self.speedBtns) {
        if (![btn isEqual:sender]) {
            btn.selected = NO;
            
        }
    }
    
}
- (void)change_status_timeBtn:(UIButton *)sender {
    sender.selected = YES;
    
    
    
        [self.coutDownBtn setTitle:[NSString stringWithFormat: @"00:%@:00", [sender.currentTitle componentsSeparatedByString:@"分钟"].firstObject] forState:UIControlStateNormal];

    
    for (UIButton *btn in self.timeBtns) {
        if (![btn isEqual:sender]) {
            btn.selected = NO;
            
        }
    }
   
}
- (IBAction)startBtnClick:(UIButton *)sender {
    
    if (self.counting) {
        return;
    }
    //{"cmd":"dev","data":[{"reg":"range_level","value":"1"},{"reg":"time","value":"2020-03-20 09:58:49/2020-03-20 10:13:49"}],"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","index":20}
    sender.userInteractionEnabled = NO;
//    NSUInteger second = 60;
//

    
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;

    NSMutableArray *dataArr = [NSMutableArray array];
    
    for (UIButton *s_btn in self.speedBtns) {
        if (s_btn.selected) {
            [dataArr addObject:@{
                                 @"reg" : @"range_level"
                                 , @"value" : @(s_btn.tag + 1)
                                 }];
            break;
        }
    }
    
    for (UIButton *t_btn in self.timeBtns) {
        if (t_btn.selected) {
            NSInteger mins = [t_btn.currentTitle componentsSeparatedByString:@"分钟"].firstObject.integerValue;
            
            [dataArr addObject:@{
                                 @"reg" : @"time"
                                 , @"value" : [self time_reg_value_str:mins]
                                 }];
            break;
        }
    }
    
    
    [vc queryWith_cmd:@"dev" data:dataArr];
    
    sender.userInteractionEnabled = YES;
    
    
}
- (IBAction)stopBtnClick:(UIButton *)sender {
    if (!self.counting) {
        return;
    }
    // {"cmd":"dev","data":[{"reg":"time","value":"2020-03-20 10:02:46/2020-03-20 10:02:46"}],"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","index":21}
    //{"dev_id":"IF-YA-HBB-19A-C44F3314ECF5-6300","dev_type":"YA-HBB-19A","cmd":"dev_execute","index":0,"data":[{"reg":"time","value":"2020-03-20 10:02:46/2020-03-20 10:02:46"}]}
    
    
    
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;

    NSMutableArray *dataArr = [NSMutableArray array];
    
    
    
    [dataArr addObject:@{
                         @"reg" : @"time"
                         , @"value" : [self time_reg_value_str:0]
                         }];
    
    [vc queryWith_cmd:@"dev" data:dataArr];
    

    
    sender.userInteractionEnabled = NO;
    [self.coutDownBtn stopCountDown];
    self.progressView.progress = 0;
    
    sender.userInteractionEnabled = YES;
}
- (NSString *)time_reg_value_str:(NSInteger)mins{
    
    NSDate * d1 = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init ];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * dateStr1 = [dateFormatter stringFromDate:d1];
    
    
    
    NSDate *d2 = [d1 dateByAddingMinutes:mins];
    
    NSString * dateStr2 = [dateFormatter stringFromDate:d2];
    
    NSLog(@"%@/%@", dateStr1, dateStr2);
    
    return [NSString stringWithFormat:@"%@/%@",dateStr1, dateStr2];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.groupTableViewBackgroundColor;

    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if (vc.entity.is_virtual == NO) {
        self.stopBtn.userInteractionEnabled = NO;
        self.startBtn.userInteractionEnabled = NO;
        for (UIButton *b in self.speedBtns) {
            b.userInteractionEnabled = NO;
        }
        for (UIButton *b in self.timeBtns) {
            b.userInteractionEnabled = NO;
        }
    }
    

    //默认
    UIButton *speedBtn = self.speedBtns.firstObject;
    speedBtn.selected = YES;
    
    UIButton *timeBtn = self.timeBtns.firstObject;
    timeBtn.selected = YES;
    
    self.speed_sel_bg_img = [Anktool gradient_img_create:rgb(141,213,255) toColor:rgb(140,191,255) frame:speedBtn.frame];
    
    self.time_normal_bg_img = self.speed_normal_bg_img = [UIImage qmui_imageWithColor:rgb(247,247,247)];
    self.time_sel_bg_img = [Anktool gradient_img_create:rgb(252,206,180) toColor:rgb(250,192,145) frame:timeBtn.frame];
     
    
    
    for (UIButton *b in self.speedBtns) {
        [b setBackgroundImage:self.speed_normal_bg_img forState:UIControlStateNormal];
        [b setBackgroundImage:self.speed_sel_bg_img forState:UIControlStateSelected];
    }
    for (UIButton *b in self.timeBtns) {
        [b setBackgroundImage:self.time_normal_bg_img forState:UIControlStateNormal];
        [b setBackgroundImage:self.time_sel_bg_img forState:UIControlStateSelected];
    }
    
    UIImage *start_stop_btn_bg_img = [UIImage qmui_imageWithColor:rgb(231,228,231)];
    [self.startBtn setBackgroundImage:UIImageMake(@"start_btn") forState: UIControlStateNormal];
    [self.startBtn setBackgroundImage:start_stop_btn_bg_img forState:UIControlStateSelected];
    
    [self.stopBtn setBackgroundImage:start_stop_btn_bg_img forState:UIControlStateNormal];
    [self.stopBtn setBackgroundImage:UIImageMake(@"start_btn") forState:UIControlStateSelected];

    
    
    [self addCircle];
    [self.coutDownBtn setTitle:[NSString stringWithFormat: @"00:15:00"] forState:UIControlStateNormal];
    
    
    
    [self.coutDownBtn countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
        self.counting = NO;
//        [self change_status_timeBtn:self.timeBtns[0]];
        self.startBtn.selected = self.stopBtn.selected = NO;
        for (UIButton *btn in self.timeBtns) {
            if (btn.selected) {
                NSInteger mins = [btn.currentTitle componentsSeparatedByString:@"分钟"].firstObject.integerValue;
                return [NSString stringWithFormat: @"00:%ld:00", (long)mins];
            }
        }
        return [NSString stringWithFormat: @"00:15:00"];
        
    }];
    
    [self.coutDownBtn countDownChanging:^NSString *(JKCountDownButton *countDownButton, NSUInteger secondsCountDown) {
        NSTimeInterval zongshijian = self.totalInterval;
        self.progressView.progress = (secondsCountDown / zongshijian);
        // 重新计算 时/分/秒
        NSString *str_hour = [NSString stringWithFormat:@"%02ld", secondsCountDown / 3600];
        NSString *str_minute = [NSString stringWithFormat:@"%02ld", (secondsCountDown % 3600) / 60];
        NSString *str_second = [NSString stringWithFormat:@"%02ld", secondsCountDown % 60];
        NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@", str_hour, str_minute, str_second];
        return format_time;

    }];
    
    

}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    [vc query_page_info];
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];

    self.cycle_lb.layer.masksToBounds = YES;
    self.cycle_lb.layer.cornerRadius = CGRectGetHeight(self.cycle_lb.frame) * 0.5;
    self.coutDownBtn.layer.masksToBounds = YES;
    self.coutDownBtn.layer.cornerRadius = CGRectGetHeight(self.coutDownBtn.frame) * 0.5;

}
- (IBAction)light_switch_action:(UISwitch *)sender {
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if(!vc.handshake_yes) return;
    NSArray *default_reg_dataArr = @[
        @{
            @"reg" : @"lights_sw"//  音量
            ,@"value" : sender.isOn == YES ? @"open" : @"close"
        }
    ];
    [vc queryWith_cmd:@"dev" data:default_reg_dataArr];
    
    
    if (sender.isOn) {
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:app_code forKey:@"appCode"];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
        [dict setObject:vc.deviceInfo.data.device_id forKey:@"deviceId"];
        
        [PPHTTPRequest req:@"java/app/device/openNightLight" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
            }
            else{
                [QMUITips showError:response[@"error_msg"] ];
            }
        } failure:^(NSError *error) {
            [QMUITips showError:[error localizedDescription]];
        }];
    }
    
   
}
-(void)addCircle {
//    float lineWidth = 10;
//
//    WTCircleProgressView *circleView = [[WTCircleProgressView alloc]initWithFrame:CGRectMake(0, -100, 100, 100) lineWidth:lineWidth];
////    circleView = [[WTCircleProgressView alloc]initWithFrame:self.cycle_lb.frame lineWidth:lineWidth];
//
//    self.circleView = circleView;
//    circleView.center = self.view.center;
//    circleView.totalTime = 5.0;
//    [self.holder_v addSubview:circleView];
//
//    [circleView start:^{
//        NSLog(@"ff");
//    }];
    
    // 背景色
    self.progressView.trackBackgroundColor = rgb(255, 211, 222);
    // 进度颜色
    self.progressView.trackColor = appMainColor;
    self.progressView.lineWidth = 8;
    self.progressView.headerImage = [UIImage imageNamed:@"yaobai_count_cap"];
    // 开始角度位置
    //    self.progressView.beginAngle =
    // 自定义progressLabel的属性...
    self.progressView.progressLabel.textColor = [UIColor lightGrayColor];
        self.progressView.progressLabel.hidden = YES;
    
    
}

- (UIImage *)drawImage {
    UIGraphicsBeginImageContext(CGSizeMake(20, 20));
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextAddArc(currentContext, 10, 10, 10, 0, 2*M_PI, 0);
    [[UIColor blueColor] set];
    CGContextFillPath(currentContext);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}




@end

